package com.okbihuo.perm.core.logger.publisher;

import com.okbihuo.perm.core.tool.utils.SpringUtil;
import com.okbihuo.perm.core.logger.constant.LogLevel;
import com.okbihuo.perm.core.logger.domain.LogRecord;
import com.okbihuo.perm.core.logger.event.LogEvent;
import com.okbihuo.perm.core.tool.utils.ObjectUtil;
import com.okbihuo.perm.core.tool.utils.UrlUtil;
import com.okbihuo.perm.core.tool.utils.WebUtil;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * 日志信息事件发送
 */
@Slf4j
public class LogPublisher {

    public static void publishEvent(LogLevel logLevel, String logUnique, String data) {
        // 补充request信息
        HttpServletRequest request = WebUtil.getRequest();
        LogRecord log = new LogRecord();
        log.setLogLevel(logLevel.name());
        log.setLogUnique(logUnique);
        log.setLogData(data);
        Thread thread = Thread.currentThread();
        StackTraceElement[] trace = thread.getStackTrace();
        if (trace.length > 3) {
            log.setMethodClass(trace[3].getClassName());
            log.setMethodName(trace[3].getMethodName());
        }
        addRequestInfoToLog(request, log);
        LogEvent event = new LogEvent(log);
        SpringUtil.publishEvent(event);
    }
    public static void info(String id, String data) {
        LogPublisher.publishEvent(LogLevel.info, id, data);
    }

    public static void debug(String id, String data) {
        LogPublisher.publishEvent(LogLevel.debug, id, data);
    }

    public static void warn(String id, String data) {
        LogPublisher.publishEvent(LogLevel.warn, id, data);
    }

    public static void error(String id, String data) {
        LogPublisher.publishEvent(LogLevel.error, id, data);
    }


    /**
     * 向log中添加补齐request的信息
     *
     * @param request     请求
     * @param logAbstract 日志基础类
     */
    private static void addRequestInfoToLog(HttpServletRequest request, LogRecord logAbstract) {
        if (ObjectUtil.isNotEmpty(request)) {
            logAbstract.setRemoteIp(WebUtil.getIP(request));
            logAbstract.setUserAgent(request.getHeader(WebUtil.USER_AGENT_HEADER));
            logAbstract.setRequestUri(UrlUtil.getPath(request.getRequestURI()));
            logAbstract.setMethod(request.getMethod());
            logAbstract.setParams(WebUtil.getRequestContent(request));
            try {
                logAbstract.setBodyData(WebUtil.getRequestBody(request.getInputStream()));
            } catch (IOException e) {
                log.info("获取post请求数据失败:"+e.getMessage());
            }
        }
    }

}
